
<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { getImgUrl } from "#/utils/getImgUrl"

const props = defineProps({
  src: { type: String, required: true },  // 图片地址（可异步拼接）
  alt: { type: String, default: '' },     // alt 文本
  imgStyle: { type: Object, default: () => ({}) }, // 自定义样式
  showPreview: {type: Boolean, default: false} // 预览
});

const emit = defineEmits(['imageLoaded'])

const refSrc = ref()
const imgLoaded = ref(false)
// 图片加载逻辑
async function loadImage(path:any) {
  const src = await getImgUrl(path) as any
  const base64Content = arrayBufferToImageBase64(src)
  const img = new Image() as any
  refSrc.value = base64Content
  img.src = base64Content
  img.crossorigin = 'anonymous'
  img.onload = () => {
    console.log('已加载')
    imgLoaded.value = true
  };
  img.onerror = () => {
    console.log('加载失败')
    imgLoaded.value = false
  };
}

function arrayBufferToImageBase64(buffer: ArrayBuffer, mimeType: string = 'image/png'): string {
  const bytes = new Uint8Array(buffer)
  let binary = '';
  bytes.forEach(byte => binary += String.fromCharCode(byte))
  return `data:${mimeType};base64,${btoa(binary)}`
}


// 监听 src 变化（适用于动态拼接的 URL）
watch(() => props.src, (newSrc) => {
  loadImage(newSrc);
});

// 初始化加载
onMounted(() => {
  loadImage(props.src);
});
</script>
<template>
  <div class="async-image">
    <el-image
      lazy
      v-show="imgLoaded"
      loading="lazy"
      :style="{width: imgStyle.width ?? '100%', height: imgStyle.height ?? 'auto'}"
      :src="refSrc"
      :zoom-rate="1.2"
      :max-scale="7"
      :min-scale="0.2"
      :preview-teleported="true"
      :preview-src-list="showPreview ? [refSrc] : []"
      show-progress
      :initial-index="4"
      fit="cover"
    />
  </div>
</template>


<style scoped>
</style>
